﻿using System;

namespace Kugar.Core.PluginFramework
{
    /// <summary>
    /// 类似于MVC中的ActionFilterAttribute,用于在调用插件函数之前,执行指定处理函数,一定程度上实现AOP功能
    /// </summary>
    public abstract class MethodFilterAttribute : Attribute
    {
        /// <summary>
        /// 函数调用之前触发
        /// </summary>
        /// <param name="args"></param>
        public virtual void OnMethodExecuting(MethodExecutingArgs filterArgs)
        {
        }

        /// <summary>
        /// 函数调用之后触发
        /// </summary>
        /// <param name="args"></param>
        /// <param name="result"></param>
        /// <param name="error"></param>
        /// <returns>返回新的结果,如无需改变,则直接返回result参数的值</returns>
        public virtual object OnMethodExecuted(object[] args, object result, Exception error)
        {
            return result;
        }

        /// <summary>
        /// 执行的顺序,根据数字从小到大执行
        /// </summary>
        public virtual int Order { set; get; } = 100;
    }

    /// <summary>
    /// 函数执行的参数
    /// </summary>
    public class MethodExecutingArgs
    {
        private object[] _paramters;

        public MethodExecutingArgs(object[] paramters)
        {
            Result = EmptyMethodFilterExecutingResult.Default;
            _paramters = paramters;
        }

        /// <summary>
        /// 调用时的参数
        /// </summary>
        public object[] Paramters => _paramters;

        /// <summary>
        /// 函数返回值,如该参数被赋值,则不会执行实际的函数,直接返回该属性指定的值
        /// </summary>
        public object Result { set; get; }
    }

    internal class EmptyMethodFilterExecutingResult
    {
        private static EmptyMethodFilterExecutingResult _default=new EmptyMethodFilterExecutingResult();

        public static EmptyMethodFilterExecutingResult Default => _default;

    }
}